package com.pdg.dungeondelver.engine;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class WeightedGenerator<T> {
	private Map<T,Integer> table = new HashMap<T,Integer>();
	private Integer totalWeight = 0;
	public void setWeight(T key,Integer weight){
		if(weight<0) weight=0;
		totalWeight-=getWeight(key);
		table.put(key,weight);
		totalWeight+=getWeight(key);
	}
	public Integer getWeight(T key){
		if(table.containsKey(key)){
			return table.get(key);
		}else{
			return 0;
		}
	}
	public T generate(RandomNumberGenerator generator){
		T result = null;
		Iterator<T> iterator = table.keySet().iterator();
		Integer generated = generator.next(totalWeight);
		while(generated>=0 && iterator.hasNext()){
			result = iterator.next();
			generated -= getWeight(result);
		}
		return result;
	}
	
}
